package com.lcq.httplib.client;

import android.util.Log;

import com.google.gson.Gson;
import com.lcq.httplib.callback.DataCallback;

import java.lang.reflect.Type;
import java.util.Map;

public class ClientParams<T> {
    private final String url;
    private final Map<String, String> headers;
    private final Object postObject;
    private final boolean post;
    private final boolean async;
    private DataCallback<T> callback;

    private ClientParams(Builder<T> builder) {
        url = builder.url;
        headers = builder.headers;
        postObject = builder.postObject;
        post = builder.post;
        async = builder.async;
        callback = builder.callback;
    }

    public String getUrl() {
        return url;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public Object getPostObject() {
        return postObject;
    }

    public boolean isPost() {
        return post;
    }

    public boolean isAsync() {
        return async;
    }

    public DataCallback<T> getCallback() {
        if (callback == null) {
            callback = new DataCallback<T>() {
                @Override
                public Type getDataType() {
                    return String.class;
                }

                @Override
                public void onSuccess(T data) {
                    Log.d("http", "onSuccess,no DataCallback:");
                }

                @Override
                public void onFail(int code, String msg) {
                    Log.d("http", "onFail,no DataCallback,code:" + code + ",msg:" + msg);
                }
            };
        }
        return callback;
    }

    public static final class Builder<T> {
        private String url;
        private Map<String, String> headers;
        private Object postObject;
        private boolean post;
        private boolean async = true;//默认异步
        private DataCallback<T> callback;

        public Builder() {
        }

        public Builder<T> url(String val) {
            Log.d("http", "client.url:" + val);
            url = val;
            return this;
        }

        public Builder<T> headers(Map<String, String> val) {
            headers = val;
            return this;
        }

        public Builder<T> postObject(Object val) {
            Log.d("http", "client.postObject:" + (val instanceof String ? val : new Gson().toJson(val)));
            postObject = val;
            post = true;
            return this;
        }

        public Builder<T> async(boolean val) {
            async = val;
            return this;
        }

        public Builder<T> callback(DataCallback<T> val) {
            callback = val;
            return this;
        }

        public ClientParams<T> build() {
            return new ClientParams<>(this);
        }
    }
}
